<script lang="ts" setup>
import Taro from "@tarojs/taro";
import { computed, onMounted, ref, useId } from "vue";

const { capsule = true } = defineProps<{
  capsule?: boolean;
  list: string[];

  center?: boolean;
}>();

const modelValue = defineModel<number>({ default: 0 });

const tabIndex = ref(modelValue);
const map = ref();
const offset = ref(10);

const id = `tabWrap_${useId()}`;
const distance = computed(() => {
  const index = modelValue.value;

  const tid = `tab_item_${id}_${index}`;
  const { width = 0, left = 0 } = map.value?.[tid] || {};

  return {
    transform: `translate(${left - offset.value}px ,50%) scale(0.75,1)`,
    width: width + "px",
  };
});

onMounted(() => {
  Taro.createSelectorQuery()
    .select("#" + id)
    .boundingClientRect()
    .exec((res) => {
      offset.value = res[0]["left"];
    });

  Taro.createSelectorQuery()
    .selectAll(".tab-item")
    .boundingClientRect()
    .exec((res) => {
      map.value = res[0].reduce((obj, item) => {
        obj[item.id] = item;
        return obj;
      }, {});
    });
});
</script>

<template>
  <view
    :id="id"
    :class="[
      'relative flex pb-2 text-sm',
      center ? 'justify-center' : 'justify-around',
    ]"
  >
    <view
      v-for="(item, index) in list"
      :key="item"
      class="tab-item relative flex-center h-[60px] rounded-full"
      :class="[
        capsule && index == modelValue ? 'text-light bg-dark' : 'text-light',
        capsule && 'px-5',
      ]"
      :id="`tab_item_${id}_${index}`"
      @tap="tabIndex = index"
      >{{ item }}
    </view>

    <view
      class="absolute bottom-0 left-0 h-[10px] rounded-full bg-white duration-200"
      :style="distance"
    />
  </view>
</template>
